package com.chiao.core;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

public class ExtNode {
	/**
	 * 节点编号
	 */
	private Integer id;
	/**
	 * 节点内容
	 */
	private String text;
	/**
	 * 父节点编号
	 */
	private Integer parentId;

	/**
	 * 排序字段
	 */
	private int sortNo;

	private List<ExtNode> children=new ArrayList<ExtNode>();

	public List<ExtNode> getChildren() {
		return children;
	}

	public void setChildren(List<ExtNode> children) {
		this.children = children;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public Integer getParentId() {
		return parentId;
	}

	public void setParentId(Integer parentId) {
		this.parentId = parentId;
	}

	public int getSortNo() {
		return sortNo;
	}

	public void setSortNo(int sortNo) {
		this.sortNo = sortNo;
	}

	// 先序遍历，拼接JSON字符串
	@Override
	public String toString() {
		sortChildren();
		String result = "{" + "id : '" + id + "'" + ", text : '" + text + "'";
		if (children != null && children.size() != 0) {
			result += ", children : " + childrenStr();
		} else {
			result += ", leaf : true";
		}
		return result + "}";
	}

	private String childrenStr() {
		String result = "[";
		for (Iterator it = children.iterator(); it.hasNext();) {
			result += ((ExtNode) it.next()).toString();
			result += ",";
		}
		result = result.substring(0, result.length() - 1);
		result += "]";
		return result;
	}
	
	 private void sortChildren() {     
	        Collections.sort(children, new Comparator (){
				@Override
				public int compare(Object o1, Object o2) {
					int j1 =  ((ExtNode)o1).getSortNo(); 
					int j2 =  ((ExtNode)o2).getSortNo(); 
			        return (j1 < j2 ? -1 : (j1 == j2 ? 0 : 1));  
				}
	        	
	        });     
	        for (Iterator it = children.iterator(); it.hasNext();) {     
	            ((ExtNode) it.next()).sortChildren();     
	        }     
	    } 

}